//! ZUC stream cipher algorithm
//!
//! https://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=8C41A3AEECCA52B5C0011C8010CF0715


/// S0 box
pub const S0: [u8; 256] = [
    0x3E, 0x72, 0x5B, 0x47, 0xCA, 0xE0, 0x00, 0x33, 0x04, 0xD1, 0x54, 0x98, 0x09, 0xB9, 0x6D, 0xCB,
    0x7B, 0x1B, 0xF9, 0x32, 0xAF, 0x9D, 0x6A, 0xA5, 0xB8, 0x2D, 0xFC, 0x1D, 0x08, 0x53, 0x03, 0x90,
    0x4D, 0x4E, 0x84, 0x99, 0xE4, 0xCE, 0xD9, 0x91, 0xDD, 0xB6, 0x85, 0x48, 0x8B, 0x29, 0x6E, 0xAC,
    0xCD, 0xC1, 0xF8, 0x1E, 0x73, 0x43, 0x69, 0xC6, 0xB5, 0xBD, 0xFD, 0x39, 0x63, 0x20, 0xD4, 0x38,
    0x76, 0x7D, 0xB2, 0xA7, 0xCF, 0xED, 0x57, 0xC5, 0xF3, 0x2C, 0xBB, 0x14, 0x21, 0x06, 0x55, 0x9B,
    0xE3, 0xEF, 0x5E, 0x31, 0x4F, 0x7F, 0x5A, 0xA4, 0x0D, 0x82, 0x51, 0x49, 0x5F, 0xBA, 0x58, 0x1C,
    0x4A, 0x16, 0xD5, 0x17, 0xA8, 0x92, 0x24, 0x1F, 0x8C, 0xFF, 0xD8, 0xAE, 0x2E, 0x01, 0xD3, 0xAD,
    0x3B, 0x4B, 0xDA, 0x46, 0xEB, 0xC9, 0xDE, 0x9A, 0x8F, 0x87, 0xD7, 0x3A, 0x80, 0x6F, 0x2F, 0xC8,
    0xB1, 0xB4, 0x37, 0xF7, 0x0A, 0x22, 0x13, 0x28, 0x7C, 0xCC, 0x3C, 0x89, 0xC7, 0xC3, 0x96, 0x56,
    0x07, 0xBF, 0x7E, 0xF0, 0x0B, 0x2B, 0x97, 0x52, 0x35, 0x41, 0x79, 0x61, 0xA6, 0x4C, 0x10, 0xFE,
    0xBC, 0x26, 0x95, 0x88, 0x8A, 0xB0, 0xA3, 0xFB, 0xC0, 0x18, 0x94, 0xF2, 0xE1, 0xE5, 0xE9, 0x5D,
    0xD0, 0xDC, 0x11, 0x66, 0x64, 0x5C, 0xEC, 0x59, 0x42, 0x75, 0x12, 0xF5, 0x74, 0x9C, 0xAA, 0x23,
    0x0E, 0x86, 0xAB, 0xBE, 0x2A, 0x02, 0xE7, 0x67, 0xE6, 0x44, 0xA2, 0x6C, 0xC2, 0x93, 0x9F, 0xF1,
    0xF6, 0xFA, 0x36, 0xD2, 0x50, 0x68, 0x9E, 0x62, 0x71, 0x15, 0x3D, 0xD6, 0x40, 0xC4, 0xE2, 0x0F,
    0x8E, 0x83, 0x77, 0x6B, 0x25, 0x05, 0x3F, 0x0C, 0x30, 0xEA, 0x70, 0xB7, 0xA1, 0xE8, 0xA9, 0x65,
    0x8D, 0x27, 0x1A, 0xDB, 0x81, 0xB3, 0xA0, 0xF4, 0x45, 0x7A, 0x19, 0xDF, 0xEE, 0x78, 0x34, 0x60,
];

/// S1 box
pub const S1: [u8; 256] = [
    0x55, 0xC2, 0x63, 0x71, 0x3B, 0xC8, 0x47, 0x86, 0x9F, 0x3C, 0xDA, 0x5B, 0x29, 0xAA, 0xFD, 0x77,
    0x8C, 0xC5, 0x94, 0x0C, 0xA6, 0x1A, 0x13, 0x00, 0xE3, 0xA8, 0x16, 0x72, 0x40, 0xF9, 0xF8, 0x42,
    0x44, 0x26, 0x68, 0x96, 0x81, 0xD9, 0x45, 0x3E, 0x10, 0x76, 0xC6, 0xA7, 0x8B, 0x39, 0x43, 0xE1,
    0x3A, 0xB5, 0x56, 0x2A, 0xC0, 0x6D, 0xB3, 0x05, 0x22, 0x66, 0xBF, 0xDC, 0x0B, 0xFA, 0x62, 0x48,
    0xDD, 0x20, 0x11, 0x06, 0x36, 0xC9, 0xC1, 0xCF, 0xF6, 0x27, 0x52, 0xBB, 0x69, 0xF5, 0xD4, 0x87,
    0x7F, 0x84, 0x4C, 0xD2, 0x9C, 0x57, 0xA4, 0xBC, 0x4F, 0x9A, 0xDF, 0xFE, 0xD6, 0x8D, 0x7A, 0xEB,
    0x2B, 0x53, 0xD8, 0x5C, 0xA1, 0x14, 0x17, 0xFB, 0x23, 0xD5, 0x7D, 0x30, 0x67, 0x73, 0x08, 0x09,
    0xEE, 0xB7, 0x70, 0x3F, 0x61, 0xB2, 0x19, 0x8E, 0x4E, 0xE5, 0x4B, 0x93, 0x8F, 0x5D, 0xDB, 0xA9,
    0xAD, 0xF1, 0xAE, 0x2E, 0xCB, 0x0D, 0xFC, 0xF4, 0x2D, 0x46, 0x6E, 0x1D, 0x97, 0xE8, 0xD1, 0xE9,
    0x4D, 0x37, 0xA5, 0x75, 0x5E, 0x83, 0x9E, 0xAB, 0x82, 0x9D, 0xB9, 0x1C, 0xE0, 0xCD, 0x49, 0x89,
    0x01, 0xB6, 0xBD, 0x58, 0x24, 0xA2, 0x5F, 0x38, 0x78, 0x99, 0x15, 0x90, 0x50, 0xB8, 0x95, 0xE4,
    0xD0, 0x91, 0xC7, 0xCE, 0xED, 0x0F, 0xB4, 0x6F, 0xA0, 0xCC, 0xF0, 0x02, 0x4A, 0x79, 0xC3, 0xDE,
    0xA3, 0xEF, 0xEA, 0x51, 0xE6, 0x6B, 0x18, 0xEC, 0x1B, 0x2C, 0x80, 0xF7, 0x74, 0xE7, 0xFF, 0x21,
    0x5A, 0x6A, 0x54, 0x1E, 0x41, 0x31, 0x92, 0x35, 0xC4, 0x33, 0x07, 0x0A, 0xBA, 0x7E, 0x0E, 0x34,
    0x88, 0xB1, 0x98, 0x7C, 0xF3, 0x3D, 0x60, 0x6C, 0x7B, 0xCA, 0xD3, 0x1F, 0x32, 0x65, 0x04, 0x28,
    0x64, 0xBE, 0x85, 0x9B, 0x2F, 0x59, 0x8A, 0xD7, 0xB0, 0x25, 0xAC, 0xAF, 0x12, 0x03, 0xE2, 0xF2,
];

/// d constants
pub const D: [u16; 16] = [
    0b_0100_0100_1101_0111, 0b_0010_0110_1011_1100, 0b_0110_0010_0110_1011, 0b_0001_0011_0101_1110,
    0b_0101_0111_1000_1001, 0b_0011_0101_1110_0010, 0b_0111_0001_0011_0101, 0b_0000_1001_1010_1111,
    0b_0100_1101_0111_1000, 0b_0010_1111_0001_0011, 0b_0110_1011_1100_0100, 0b_0001_1010_1111_0001,
    0b_0101_1110_0010_0110, 0b_0011_1100_0100_1101, 0b_0111_1000_1001_1010, 0b_0100_0111_1010_1100,
];

/// 线性反馈移位寄存器 `LFSR`
struct LFSR {
    /// 16 个 31 比特寄存器单元变量 s0 ... s15
    s: [u32; 16]
}

impl LFSR {
    /// 创建并初始化 `LFSR`
    #[inline(always)]
    fn create(key: &[u8; 16], iv: &[u8; 16]) -> Self {
        let mut s = [0; 16];
        for i in 0..16 {
            s[i] = (key[i] as u32) << 23 | (D[i] as u32) << 8 | iv[i] as u32;
        }
        Self { s }
    }

    /// `LFSR` 初始化模式 
    /// 
    /// `LFSRWithInitialisationMode(u)` 
    #[inline(always)]
    fn init_mode(&mut self, u: u32) {
        const W: [(u32, usize); 5] = [(1 << 15, 15), (1 << 17, 13), (1 << 21, 10), (1 << 20, 4), (1 + (1 << 8), 0)];
        let v = W.into_iter()
            .fold(0, |acc, (wi, i)|
                Self::mod_add(acc, Self::mod_mul(self.s[i], wi))
            );
        let mut s16 = Self::mod_add(v, u);
        if s16 == 0 {
            s16 = 0x7FFFFFFF; // 2 << 31 - 1
        }
        self.s.copy_within(1.., 0);
        self.s[15] = s16;
    }

    /// `LFSR` 工作模式 
    /// 
    /// `LFSRWithWorkMode()` 
    #[inline(always)]
    fn work_mode(&mut self) {
        self.init_mode(0);
    }
    
    /// 获取 `BR` 所需数据
    #[inline(always)]
    fn get_br_data(&self) -> [u32; 8] {
        [self.s[0], self.s[2], self.s[5], self.s[7], self.s[9], self.s[11], self.s[14], self.s[15]]
    }

    /// 模 (2^31 - 1) 加法
    #[inline(always)]
    const fn mod_add(a: u32, b: u32) -> u32 {
        let c = a + b;
        (c & 0x7FFFFFFF) + (c >> 31)
    }

    /// 左循环移位 (31 位)
    #[inline(always)]
    const fn left_circular_shift_31(x: u32, shift: u32) -> u32 {
        let shift = shift % 31; // 确保移位小于 31
        ((x << shift) & 0x7FFFFFFF) | (x >> (31 - shift))
    }

    /// 模 (2^31 - 1) 乘法
    #[inline(always)]
    const fn mod_mul(a: u32, b: u32) -> u32 {
        let mut result = 0;
        let mut shift = 0;
        let mut temp_b = b;

        while temp_b > 0 {
            if temp_b & 1 == 1 {
                result = Self::mod_add(result, Self::left_circular_shift_31(a, shift));
            }
            temp_b >>= 1;
            shift += 1;
        }

        result
    }
}

/// 比特重组 `BR`
#[allow(non_snake_case)]
struct BR;

impl BR {
    /// `BitReconstruction()`
    #[inline(always)]
    const fn bit_reconstruction(s: [u32; 8]) -> (u32, u32, u32, u32) {
        (
            ((s[7] << 1) & 0xFFFF_0000) | (s[6] & 0xFFFF),
            ((s[5] & 0xFFFF) << 16 ) | (s[4] >> 15),
            ((s[3] & 0xFFFF) << 16 ) | (s[2] >> 15),
            ((s[1] & 0xFFFF) << 16 ) | (s[0] >> 15),
        )
    }
}

/// 非线性函数 `F`
#[allow(non_snake_case)]
struct F {
    /// 32 比特记忆单元变量 R1
    R1: u32,
    /// 32 比特记忆单元变量 R2
    R2: u32,
}

impl F {
    /// 初始化非线性函数 `F` 并将 `R1` `R2` 置零
    #[inline(always)]
    fn init() -> Self {
        Self {
            R1: 0,
            R2: 0,
        }
    }

    /// `F(X0, X1, X2)` 逻辑部分
    #[inline(always)]
    #[allow(non_snake_case)]
    fn F(&mut self, X0: u32, X1: u32, X2: u32) -> u32 {
        let (R1, R2) = (&mut self.R1, &mut self.R2);
        let W = (X0 ^ *R1).wrapping_add(*R2);
        let W1 = R1.wrapping_add(X1);
        let W2 = *R2 ^ X2;
        *R1 = Self::S(Self::L1((W1 << 16) | (W2 >> 16)));
        *R2 = Self::S(Self::L2((W2 << 16) | (W1 >> 16)));
        W
    }

    /// 32 比特线性变换 `L1`
    #[inline(always)]
    #[allow(non_snake_case)]
    fn L1(x: u32) -> u32 {
        x ^ x.rotate_left(2) ^ x.rotate_left(10) ^ x.rotate_left(18) ^ x.rotate_left(24)
    }

    /// 32 比特线性变换 `L2`
    #[inline(always)]
    #[allow(non_snake_case)]
    fn L2(x: u32) -> u32 {
        x ^ x.rotate_left(8) ^ x.rotate_left(14) ^ x.rotate_left(22) ^ x.rotate_left(30)
    }

    /// 32 比特 `S盒` 变换 `S`
    #[inline(always)]
    #[allow(non_snake_case)]
    fn S(x: u32) -> u32 {
        let x = x.to_be_bytes();
        let y = [S0[x[0] as usize], S1[x[1] as usize], S0[x[2] as usize], S1[x[3] as usize]];
        u32::from_be_bytes(y)
    }
}

/// ZUC-128 加密机
#[allow(non_snake_case)]
pub struct ZUC {
    LFSR: LFSR,
    BR: fn([u32; 8]) -> (u32, u32, u32, u32),
    F: F,
}

impl ZUC {
    /// 使用指定 `k`、`iv` 初始化 ZUC 加密机
    #[inline(always)]
    #[allow(non_snake_case)]
    pub fn init(key: &[u8; 16], iv: &[u8; 16]) -> Self {
        let mut zuc = Self{
            LFSR: LFSR::create(key, iv),
            BR: BR::bit_reconstruction,
            F: F::init(),
        };
        for _ in 0..32 {
            let (X0, X1, X2, _) = (zuc.BR)(zuc.LFSR.get_br_data());
            let W = zuc.F.F(X0, X1, X2);
            zuc.LFSR.init_mode(W >> 1);
        }
        zuc.generate();
        zuc
    }

    /// 使用随机 `k`、`iv` 初始化的 ZUC 加密机生成指定长度 `L` 的密钥流, 并返回加密机和初始化参数
    #[inline(always)]
    #[allow(non_snake_case)]
    pub fn init_random_key_zuc() -> (([u8; 16], [u8; 16]), Self) {
        let key = rand::random::<[u8; 16]>();
        let iv = rand::random::<[u8; 16]>();
        ((key, iv), ZUC::init(&key, &iv))
    }

    /// 使 ZUC 加密机输出 32 比特密钥字 `Z`
    #[inline(always)]
    #[allow(non_snake_case)]
    pub fn generate(&mut self) -> u32 {
        let (X0, X1, X2, X3) = (self.BR)(self.LFSR.get_br_data());
        let Z = self.F.F(X0, X1, X2) ^ X3;
        self.LFSR.work_mode();
        Z
    }

    /// 使用指定 `k`、`iv` 初始化的 ZUC 加密机生成指定长度 `L` 的密钥流
    ///
    /// 返回密钥流长度是 32 比特密钥字 `Z` 的整数倍, 可能大于 `L`
    #[inline(always)]
    #[allow(non_snake_case)]
    pub fn generate_keystream_block(key: &[u8; 16], iv: &[u8; 16], L: usize) -> Vec<u8> {
        ZUC::init(key, iv).into_iter().take((L as f64 / 4_f64).ceil() as usize)
            .map(|block| block.to_be_bytes())
            .collect::<Vec<_>>().concat()
    }

    /// 使用指定 `k`、`iv` 初始化的 ZUC 加密机生成指定长度 `L` 的密钥流
    /// 
    /// 返回密钥流长度是指定长度 `L`
    #[inline(always)]
    #[allow(non_snake_case)]
    pub fn generate_keystream(key: &[u8; 16], iv: &[u8; 16], L: usize) -> Vec<u8> {
        Self::generate_keystream_block(key, iv, L)[..L].to_vec()
    }

    /// 使用随机 `k`、`iv` 初始化的 ZUC 加密机生成指定长度 `L` 的密钥流, 并返回密钥流和初始化参数
    /// 
    /// 返回密钥流长度是指定长度 `L`
    #[inline(always)]
    #[allow(non_snake_case)]
    pub fn generate_random_keystream(L: usize) -> (([u8; 16], [u8; 16]), Vec<u8>) {
        let key = rand::random::<[u8; 16]>();
        let iv = rand::random::<[u8; 16]>();
        ((key, iv), Self::generate_keystream(&key, &iv, L))
    }
}

impl Iterator for ZUC {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        Some(self.generate())
    }
}


#[cfg(test)]
mod test {
    use super::ZUC;

    #[test]
    fn test() {
        let (_, mut zuc) = ZUC::init_random_key_zuc();

        for _ in 0..10 {
            println!("{:x}", zuc.generate())
        }
    }
}